﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singer.Middleware.EFCore
{
    public static class EFCoreServiceExtensions
    {
        public static void AddEFCore<TDbContext>(this IServiceCollection services, IConfiguration configuration)
            where TDbContext : EFCoreDbContext
        {
            EFCoreOptions? options = configuration.GetSection(EFCoreOptions.ConfigKey).Get<EFCoreOptions>();
            if (options == null)
                throw new Exception("【EFCore】Config was not found.");
            options.Validate();
            services.Configure<EFCoreOptions>(configuration.GetSection(EFCoreOptions.ConfigKey));
            Action <DbContextOptionsBuilder> builderAcion = null;
            switch (options.DataType)
            {
                case DataType.SqlServer:
                    builderAcion = opt => opt.UseSqlServer(options.ConnectionString);
                    break;
                default:
                    throw new Exception($"【EFCore】This DataType '{options.DataType}' was not supported.");
            }
            services.AddDbContext<TDbContext>(builderAcion);
        }
    }
}
